<?php

	// +----------------------------------------------------------------------
	// | 用户管理
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\controller\ucenter\admin;

	use app\controller\admin\Common;
	use app\common\middleware\UserAuth;
	use app\model\ucenter\User as UserModel;
	use app\event\ucenter\User as UserEvent;
	use app\event\ucenter\Sms as SmsEvent;
	use app\event\ucenter\Email as EmailEvent;
	use think\facade\Session;
	use yicmf\builder\Edit;
	use yicmf\builder\Table;
	use think\facade\Url;

	class Agent extends Common
	{
		protected function initialize()
		{
			parent::initialize();
			$this->model = new UserModel();
		}


		public function index()
		{
			$map[] = ['status', '>', -2];
			$map[] = ['is_agency', '=', 1];
			// ID 姓名 手机号 推广码 等级 余额 上级 推荐人 注册时间 状态 操作
			$builder = new Table();
			$builder->model(UserModel::class)
				->where($map)
//				->excel()
				->order('id DESC')
				//                ->suggest('管理用户信息')
				->searchTextLike('nickname', '用户昵称')
				->searchText('mobile', '手机号')
//				->buttonUpdate('ucenter/admin/User/update', '新增')
				->keyId()
//                ->keyText('account', '用户账号')
				->keyText('nickname', '昵称')
				->keyText('username', '用户名')
				->keyText('mobile', '手机')
//				->keyText('F{$data.shareCode}', '推广码')
                ->keyClosure('推广码',function ($data)
                {
                    return 'F'.$data['shareCode'];
                })
				->keyText('level', '等级')
				->keyText('money', '余额')
				->keyText('my_balance', '专享资金')
				->keyText('deposit_agent', '保证金')
				->keyText('pid', '上级')
				->keyText('bid', '推荐人')
//				->keyUser('invite_id', '邀请人')
				->keyTime('agency_time', '加入时间')
//				->keyStatus()
//				->actionUpdate('pid?id={$id}','上级')
//				->actionUpdate('money?id={$id}','余额')
//				->actionUpdate('level?id={$id}','等级')
//				->actionUpdate('pwd?id={$id}', '密码', [], true)
				//             ->actionUpdate('ucenter/admin/AuthGroup/group?id={$id}', '授权')
//				->actionRestore()
//				->actionForbid('forbid?id={$id}','禁用',[1])
//				->actionDelete()
			;//修改上级  修改余额 账号冻结  修改等级
			return $builder->fetch();
		}

		public function blacklist()
		{
			$map[] = ['status', '=', -1];
			// 黑名单
			$builder = new Table();
			$builder->model(UserModel::class)
				->where($map)
				->order('id DESC')
				->searchTextLike('nickname', '用户昵称')
				->searchText('mobile', '手机号')
				->keyId()
				->keyText('email', '邮箱')
				->keyText('mobile', '手机')
				->keyText('nickname', '用户昵称')
				->keyText('balance', '余额')
				->keyTime('last_login_time', '最近登陆')
				->keyStatus()
				->actionRestore();
			return $builder->fetch();
		}

        public function info()
        {
            return $this->fetch();
        }
		public function pwd()
		{
			if ($this->request->isPost()) {
				$param = $this->request->param();
				$param['password'] = $param['new_password'];
				$param['password_confirm'] = $param['password'];

				$event = new UserEvent();
				$result = $event->adminChangePassword($param, $this->user);
				if (0 == $result['code']) {
					$this->_returnSuccess($result['message']);
				} else {
					$this->_returnError($result['message']);
				}
			} else {
				$id = $this->request->get('id', 0);
				if ($id) {
					$data = UserModel::where('id', $id)->find();
					if (!$data) {
						$this->_returnError('用户信息不存在');
					}
					// 查询权限组
					$role = $data->roles()->find();
					if ($role) {
						$data['auth_group_ids'] = $role['id'];
					} else {
						$data['auth_group_ids'] = 101;
					}
				} else {
					$data = [];
//					$data['is_vip'] = 0;
					$data['password'] = '000000';
				}
				$builder = new Edit();
				$builder->title('修改密码');
				$builder->keyHidden('id');
					$builder->keyPassword('new_password', '新密码', '密码至少要求6个字符')

					->data($data)
					->buttonSubmit();
				return $builder->fetch();
			}
		}

		public function update()
		{
			if ($this->request->isPost()) {
				$param = $this->request->param();
				if (!$param['id']) {
					$param['password_confirm'] = $param['password'];
					$result = $this->validate($param, 'User.register');
				} else {
					$result = $this->validate($param, 'User.update');
				}
				if ($result !== true) {
					$this->_returnError('用户数据验证失败：' . $result);
				}
				$event = new UserEvent();
				$result = $event->updateByAdmin($param, $this->user);
				if (0 == $result['code']) {
					$this->_returnSuccess($result['message']);
				} else {
					$this->_returnError($result['message']);
				}
			} else {
				$id = $this->request->get('id', 0);
				if ($id) {
					$data = UserModel::where('id', $id)->find();
					if (!$data) {
						$this->_returnError('用户信息不存在');
					}
					// 查询权限组
//					$role = $data->roles()->find();
//					if ($role) {
//						$data['auth_group_ids'] = $role['id'];
//					} else {
//						$data['auth_group_ids'] = 101;
//					}
				} else {
					$this->_returnError('用户信息不存在');
				}

//				$grade = \app\model\ucenter\UserGrade::where('status', 1)->column('name', 'id');
//				$data['order'] = $data->orders()->where('status', '>', -2)->count();
				$builder = new Edit();
				$builder->title('用户详情');

				$builder
                    ->keyReadOnly('username', '用户名', '不可编辑')
					->keyTextInline('nickname', '昵称', '可重复')
					->keyImageModel('avatar', '头像')
//					->keyTextInline('email', '邮箱')
					->keyMobile('mobile', '手机')
//					->keySelect('user_grade_id', '会员等级', $grade)
					->keySex()
//					->keyDate('birthday', '生日')
					->keyText('qq', 'qq')
//					->keyLabel('create_time', '注册时间')
//					->keyLabel('last_login_time', '最后登录')
//					->keyLabel('point', '积分',)
//					->keyLabel('balance', '余额', '更多<a style="cursor:pointer " lay-href="' . url('pay/admin/UserBalance/index?user_id=' . $data['id']) . '" >详情点这里</a>')
//					->keyLabel('order', '订单数', '更多<a style="cursor:pointer " lay-href="' . url('merchant/Order/index?user_id=' . $data['id']) . '" >详情点这里</a>')
//					->keyHtml('add',$html,'标题')
//                    ->keyText('website', '站点')
//                    ->keyTextArea('introduction', '个性签名')
//                    ->keyBool('is_vip', '是否金牌卖家')

//					->group('基本信息', 'account,nickname,avatar_id,email,mobile,user_grade_id,sex,birthday')
//					->group('账户信息', 'create_time,last_login_time,point,balance,order')
//					->group('地址', 'add')
					->data($data);
//				if (UserEvent::isAdministrator($this->user)) {
//					$builder->buttonSubmit();
//				}
				return $builder->fetch();
			}
		}

		public function add()
		{
			if ($this->request->isPost()) {
				$param = $this->request->param();
				if (!$param['id']) {
					$param['password_confirm'] = $param['password'];
					$result = $this->validate($param, 'User.register');
				} else {
					$result = $this->validate($param, 'User.update');
				}
				if ($result !== true) {
					$this->_returnError('用户数据验证失败：' . $result);
				}
				$event = new UserEvent();
				$result = $event->updateByAdmin($param, $this->user);
				if (0 == $result['code']) {
					$this->_returnSuccess($result['message']);
				} else {
					$this->_returnError($result['message']);
				}
			} else {
				$id = $this->request->get('id', 0);
				if ($id) {
					$data = UserModel::where('id', $id)->find();
					if (!$data) {
						$this->_returnError('用户信息不存在');
					}
					// 查询权限组
					$role = $data->roles()->find();
					if ($role) {
						$data['auth_group_ids'] = $role['id'];
					} else {
						$data['auth_group_ids'] = 101;
					}
				} else {
					$data = [];
//					$data['is_vip'] = 0;
					$data['password'] = '000000';
				}

				$grade = \app\model\ucenter\UserGrade::where('status', 1)->column('name', 'id');

				$builder = new Edit();
				$builder->title($id ? '编辑用户' : '新增用户');

				$builder->keyReadOnly('account', '用户名', '不可编辑')
					->keyTextInline('nickname', '昵称', '可重复')
					->keyImageModel('avatar_id', '头像')
					->keyTextInline('email', '邮箱')
					->keyMobile('mobile', '手机')
					->keySelect('user_grade_id', '会员等级', $grade)
					->keySex()
					->keyDate('birthday', '生日')
//                    ->keyText('qq', 'qq')
//                    ->keyText('wechat', '微信')
//                    ->keyText('website', '站点')
//                    ->keyTextArea('introduction', '个性签名')
//                    ->keyBool('is_vip', '是否金牌卖家')
					->data($data)
					->buttonSubmit();
				return $builder->fetch();
			}
		}

		public function find()
		{
			if ($this->request->isPost()) {
				$user = $this->model->where('id|account', $this->request->post('account'))->find();
				if ($user) {
					$data['code'] = 0;
					$data['data'] = $user;
				} else {
					$data['code'] = 1;
					$data['message'] = '暂无';
				}
				return json($data);
			} else {
				$this->assign('users', $this->model->all());
				$this->assign('value', $this->request->get('value', ''));
				$this->assign('callback', $this->request->get('callback'));
				return $this->fetch();
			}
		}

		public function forbid()
		{
			$course = UserModel::where('id', $this->request->param('id'))->find();
			if ($course) {
				$course['status'] = -1;
				if ($course->save()) {
					$this->_returnSuccess('禁用成功');;
				} else {
					$this->_returnError('禁用失败');
				}
			} else {
				$this->_returnError('操作异常');
			}
		}

		public function restore()
		{
			$course = UserModel::where('id', $this->request->param('id'))->find();
			if ($course) {
				$course['status'] = 1;
				if ($course->save()) {
					$this->_returnSuccess('还原成功');;
				} else {
					$this->_returnError('还原失败');
				}
			} else {
				$this->_returnError('操作异常');
			}
		}


		/**
		 * 修改密码
		 * @return mixed
		 * @throws \Exception
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function password()
		{
			if ($this->request->isPost()) {
//				if (false === UserEvent::checkPassword($this->request->post('old_password'), $this->user)) {
//					$this->_returnError('旧密码验证失败');
//				} else {
//					$result = $this->validate($this->request->post(), 'User.changepassword');
//					if (true !== $result) {
//						$this->_returnError($result);
//					} else {
				$event = new UserEvent();
				$result = $event->updatePassword($this->request->post(), $this->user);
				if (0 === $result['code']) {
					$this->_returnSuccess('密码修改成功！', true);
				} else {
					$this->_returnError('修改失败，错误信息：' . $result['message']);
				}
//					}
//				}
			} else {
				$builder = new Edit();
				$builder->title('修改密码')
//					->keySafeCheck('mobile,email', '安全检测')
					->keyPassword('old_password', '旧密码')
					->keyPassword('password_confirm', '新密码')
					->keyPassword('password', '确认新密码')
//					->data($this->user)
					->buttonSubmit('password', '提交修改');
				return $builder->fetch();
			}
		}

		/**
		 * 修改资料
		 * @return string
		 * @throws \Exception
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function profile()
		{
			if ($this->request->isPost()) {
				$result = $this->validate($this->request->post(), 'app\validate\ucenter\User.profile');
				if (true === $result) {
					$user = new UserEvent();
					$data = $user->profile($this->request->param(), $this->user);
					if (0 == $data['code']) {
						$this->_returnSuccess('资料修改成功！', true);
					} else {
						$this->_returnError('资料失败，错误信息：' . $data['message']);
					}
				} else {
					$this->_returnError('修改失败，错误信息：' . $result);
				}
			} else {
				$builder = new Edit();
				$builder->title('编辑资料')
//					->keySafeCheck('mobile,email', '安全检测')
					->keyTextInline('account', '登录名', '不可修改');
//				if (1 == $this->user['is_auth']) {
//					$builder->keyLabel('auth_name', '认证名', '不可修改');
//				}
				$builder->keyTextInline('nickname', '昵称')
					->keyTextInline('mobile', '手机')
					->keyEmail('email', '邮箱')
					->keySex('sex')
					                    ->keyImageModel('avatar_id', '头像', null, null, 2)
					//                    ->keyTextArea('introduction', '个性签名')
					->data($this->user)
					->buttonSubmit('', '保存');
				return $builder->fetch();
			}
		}

		/**
		 * 更新在线时长
		 * @return \think\response\Json
		 * @throws \Exception
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function online()
		{

			if (!Session::has('last_active_time') || Session::get('last_active_time') !== time()) {
				Session::set('last_active_time', time());
				// 控制在线时长
				$online = $this->user->onlines()->whereTime('end_time', '>', '-2 minutes')->order('id DESC')->where('ip', $this->request->ip())->find();
				if ($online) {
					$this->user['online_time'] = $this->user['online_time'] + time() - strtotime($online['end_time']);
					$this->user['last_active_time'] = time_format();
					$this->user->save();
					$online['duration'] = $online['duration'] + time() - strtotime($online['end_time']);
					$online['end_time'] = $this->user['last_active_time'];
				} else {
					// 新增记录
					$online = [];
					$online['duration'] = 1;
					$online['start_time'] = time_format();
					$online['end_time'] = time_format(time() + 1);
					$this->user->onlines()->save($online);
					$this->user['online_time'] = $this->user['online_time'] + 1;
					$this->user['last_active_time'] = $online['end_time'];
				}
				$this->user->isAutoWriteTimestamp(false)->save();
				$data['data']['online_time'] = $this->user['online_time'];

			}
			$data['data']['notice'] = $this->user->messages()->where('is_read', 0)->where('status', 1)->count('*');;
			$data['code'] = 0;
			return json($data);
		}

		public function statistics()
		{
			$result = $this->model->where('status', 1)
				->field('DATE_FORMAT(create_time,"%Y%m") days,count(id) num')->whereTime('create_time', date('Y-m-01') . ' -6 month')->group('days')->select();
			//            $chart = new Chart();
			$data = [];
			$data['tooltip'] = ['trigger' => 'axis'];
			$data['legend'] = ['data' => ['注册量']];
			$data['toolbox'] = ['show' => true, 'feature' => [
				'restore' => [
					'show' => true
				],
				'mark' => [
					'show' => false
				],
				'saveAsImage' => [
					'show' => true
				],
			]];
			$x = [];
			$series = [];
			for ($i = 6; $i >= 0; $i--) {
				$day = date('Ym', strtotime(date('Y-m-01') . ' -' . $i . '  month'));
				$num = 0;
				$x[] = $day;
				foreach ($result as $item) {
					if ($item['days'] == $day) {
						$num = $item['num'];
						break;
					}
				}
				$series[] = $num;
			}
			$data['xAxis'] = ['type' => 'category', 'data' => $x];
			$data['yAxis'] = ['type' => 'value'];
			$data['series'] = [
				['name' => '注册量', 'type' => 'line', 'data' => $series]
			];
			return json($data);
		}

		public function outxls()
		{
//			$map = $this->_search();
//			if (method_exists($this, '_filter')) {
//				$this->_filter($map);
//			}
			$list = $this->model
//				->order($this->request->get('orderField') . ' ' . $this->request->get('orderDirection'))
				->limit(2000)
				->field('id,nickname,auth_name,mobile,is_vip,income_balance,create_time')
				->select();
			$headArr = [
				'ID',
				'昵称',
				'真实姓名',
				'手机号',
				'认证讲师',
				'累积收益',
				'注册时间'
			];
			$filename = '用户导出';
			$this->excelOut($filename, $headArr, $list);
		}

		public function outxls_check()
		{
			$list = $this->model->where('id', 'in', $this->request->param('expids'))
				->field('id,nickname,auth_name,mobile,is_vip,good_at,income_balance,create_time')
				->select();
			$headArr = [
				'ID',
				'昵称',
				'真实姓名',
				'手机号',
				'认证讲师',
				'擅长',
				'累积收益',
				'注册时间'
			];
			$filename = '用户导出';
			$this->excelOut($filename, $headArr, $list);
		}
	}
